<script lang="ts">
import Vue from 'vue'
import uploadSelectPopup from "@/components/upload-select-popup/upload-select-popup.vue";
import navBar from "@/components/nav-bar/nav-bar.vue";
import tips from "@/utils/tips";
import {editImageChange} from "@/utils/utils";
import {uploadImageServer} from "@/services/office";

export default Vue.extend({
  name: "print_id_and_registration",
  components: {navBar, uploadSelectPopup},
  data() {
    return {
      idFront: '',
      idAfter: '',
      registrationFront: '',
      registrationAfter: '',
      showUploadPopup: false,
      clickType: 0,
      uploadProgress: 0,
      showUpload: false,
    }
  },
  computed: {
    lang() {
      return this.$t('print_id_and_registration')
    }
  },
  methods: {
    // 上传照片选择的
    showUploadImage(type: number) {
      this.clickType = type;
      this.showUploadPopup = true;
    },

    // 微信选取图片
    chooseMessage() {
      uni.chooseMessageFile({
        count: 1,
        type: 'image',
        success: (res) => {
          this.processImage(res.tempFiles[0].path);
        }
      });
    },
    // 本地图片上传或拍照
    chooseImage(index: string) {
      const sourceTypes = ['camera', 'album'];
      uni.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: [sourceTypes[index]],
        sizeType: ['original', 'compressed'],
        success: (res) => {
          this.processImage(res.tempFiles[0].tempFilePath);
        }
      });
    },

    // 处理图片编译
    async processImage(src: string) {
      try {
        const imagePath = await editImageChange(src);
        switch (this.clickType) {
          case 0:
            this.idFront = imagePath;
            break
          case 1:
            this.idAfter = imagePath;
            break
          case 2:
            this.registrationFront = imagePath;
            break
          case 3:
            this.registrationAfter = imagePath;
            break
        }
      } catch (error) {
        console.error('图片处理失败:', error);
      }
    },

    // 删除照片
    closeIdOrRegistration(type: number) {
      switch (type) {
        case 0:
          this.idFront = '';
          break
        case 1:
          this.idAfter = '';
          break
        case 2:
          this.registrationFront = '';
          break
        case 3:
          this.registrationAfter = '';
          break
      }
    },

    // 编译照片
    onEditImage(type: number) {
      this.clickType = type;
      let url = '';
      switch (type) {
        case 0:
          url = this.idFront;
          break
        case 1:
          url = this.idAfter;
          break
        case 2:
          url = this.registrationFront;
          break
        case 3:
          url = this.registrationAfter;
          break
      }
      this.processImage(url)
    },

    // 合成图片
    adAndRegistrationDrawAndShareImage() {
      // 绘制背景海报到canvas
      // 长143毫米，宽105毫米 户口本宽高 * 8
      const idWidth = 684;      // 身份证宽度
      const idHeight = 432;     // 身份证高度
      const registrationWidth = 1120;      // 户口宽度
      const registrationHeight = 828;     // 户口高度
      const a4Width = 1588;         // A4纸宽度
      const a4Height = 2246;        // A4纸高度

      const {idFront, idAfter, registrationFront, registrationAfter} = this;

      // 检查是否已上传照片
      if (!idFront && !idAfter && !registrationFront && !registrationAfter) {
        uni.showToast({title: "请先上传图片", icon: 'none'});
        return;
      }

      uni.showLoading({title: '加载中....', mask: true})

      // 微信小程序特有代码
      const context = uni.createCanvasContext('registrationCanvas', this);
      let ml = 70; // 身份证水平位置
      let my = (a4Height - 510 * 2) / 2 - 570; //身份证 头部
      context.fillStyle = "#FFFFFF";
      context.fillRect(0, 0, a4Width, a4Height);

      context.drawImage(idFront, ml, my, idWidth, idHeight); // 第一张身份证
      context.drawImage(idAfter, ((ml * 2) + idWidth), my, idWidth, idHeight); // 第二张身份证
      context.drawImage(registrationFront, (a4Width - registrationWidth) / 2, a4Height / 2 - 600, registrationWidth, registrationHeight); // 第一张户口本
      context.drawImage(registrationAfter, (a4Width - registrationWidth) / 2, a4Height / 2 + 258, registrationWidth, registrationHeight); // 第二张户口本

      context.draw();

      setTimeout(() => {
        uni.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: a4Width,
          height: a4Height,
          destWidth: a4Width,
          destHeight: a4Height,
          canvasId: 'registrationCanvas',
          success: (res) => {
            console.log("registrationCanvas -=-=", res);
            // 上传图片到服务器
            uni.uploadFile({
              url: uploadImageServer,
              name: 'file',
              filePath: res.tempFilePath,
              success: (res) => {
                console.log("success: (res) => -=-=-", res)
                const {code, data: {url}} = JSON.parse(res.data);
                console.log("Upload success:", JSON.parse(res.data).data);
                if (code === 200) {
                  uni.navigateTo({url: `/pages/photo_pay/photo_pay?type=1&image=` + encodeURIComponent(JSON.stringify(url))})
                }
              },
              fail: (err) => {
                console.error('Upload failed:', err);
              }, complete: () => {
                uni.hideLoading()
              }
            });
          }
        });
      }, 2000)
    },
  },
})
</script>

<template>
  <view>
    <nav-bar :pageTitle="lang.page_name"/>
    <view style="margin:0 30rpx 0 30rpx;" :class="locale">
      <view class="column gap-20 ltr print-id-and-registration-a4">

        <!-- 身份证选自框大 box-->
        <view class="flex-between">
          <!-- 身份证前面-->
          <view class="column-center gap-20">
            <view class="upload-id-card-box">
              <view v-if="idFront === ''" hover-class="hover" @click="showUploadImage(0)">
                <view class="column-center icon-card-box">
                  <view class="flex-column icon-card">
                    <u-icon size="32px" color="#1073FF" name="camera"/>
                  </view>
                </view>
                <image class="uploaded-image" src="/static/print_id/id.png"/>
              </view>

              <template v-else>
                <view class="id-close-icon-box" @click="closeIdOrRegistration(0)">
                  <u-icon size="26px" color="#0009" name="close-circle-fill"/>
                </view>
                <view @click="onEditImage(0)">
                  <image class="uploaded-image" :src="idFront"/>
                </view>
              </template>
            </view>
            <view class="text-32">{{ lang.id_front }}</view>
          </view>

          <!-- 身份证后面-->
          <view class="column-center gap-20">
            <view class="upload-id-card-box">
              <!-- 上传照片前-->
              <view v-if="idAfter===''" @click="showUploadImage(1)" hover-class="hover">
                <view class="column-center icon-card-box">
                  <view class="flex-column icon-card">
                    <u-icon size="32px" color="#1073FF" name="camera"/>
                  </view>
                </view>
                <image class="uploaded-image" src="/static/print_id/id_sel.png"/>
              </view>

              <!-- 上传照片后-->
              <template v-else>
                <view class="id-close-icon-box" @click="closeIdOrRegistration(1)">
                  <u-icon size="26px" color="#0009" name="close-circle-fill"/>
                </view>
                <view @click="onEditImage(1)">
                  <image class="uploaded-image" :src="idAfter"/>
                </view>
              </template>
            </view>
            <view class="text-32">{{ lang.id_after }}</view>
          </view>
        </view>

        <!-- 户口选自框大 box-->
        <view class="column-center gap-20">
          <!-- 户口本户主页-->
          <view class="registration-card-box">
            <view v-if="registrationFront === ''" hover-class="hover" @click="showUploadImage(2)">
              <view class="column-center icon-card-box">
                <view class="flex-column icon-card">
                  <u-icon size="44px" color="#1073FF" name="camera"/>
                </view>
              </view>
              <image class="registration" src="/static/print_id/registration.png"/>
            </view>

            <template v-else>
              <view class="close-icon-box" @click="closeIdOrRegistration(2)">
                <u-icon size="26px" color="#0009" name="close-circle-fill"/>
              </view>
              <view @click="onEditImage(2)">
                <image class="registration" :src="registrationFront"/>
              </view>
            </template>
          </view>
          <view class="text-32">{{ lang.registration_front }}</view>
        </view>

        <!-- 户口本个人页-->
        <view class="column-center gap-8" style="gap: 20rpx">
          <view class="registration-card-box">
            <view v-if="registrationAfter === ''" hover-class="hover" @click="showUploadImage(3)">
              <view class="column-center icon-card-box">
                <view class="flex-column icon-card">
                  <u-icon size="44px" color="#1073FF" name="camera"/>
                </view>
              </view>
              <image class="registration" src="/static/print_id/registration_sel.png"/>
            </view>

            <!-- 上传后-->
            <template v-else>
              <view class="close-icon-box" @click="closeIdOrRegistration(3)">
                <u-icon size="26px" color="#0009" name="close-circle-fill"/>
              </view>
              <view @click="onEditImage(3)">
                <image class="registration" :src="registrationAfter"/>
              </view>
            </template>
          </view>
          <view class="text-32">{{ `${lang.registration_after}` }}</view>
        </view>
      </view>

      <!-- 打印-->
      <view style="margin-top: 30rpx; padding: 20rpx">
        <u-button
            shape="circle" @click="adAndRegistrationDrawAndShareImage" size="large" color="#1073FF"
            :customStyle="{fontSize: '32rpx' }">
          {{ otherLang.print }}
        </u-button>
      </view>

      <!-- a4 打印-->
      <view class="canvas">
        <canvas style="width: 1588px; height: 2246px; " canvas-id="registrationCanvas" id="registrationCanvas"/>
      </view>

      <!--    上传中弹窗-->
      <!--      <my_upload_card :upload-name="lang.registration_upload" :show="showUpload" :upload-progress="uploadProgress"/>-->

      <!-- 选择弹窗-->
      <upload-select-popup
          :show-popup="showUploadPopup" @choose-message="chooseMessage" @choose-image="chooseImage"
          @close-popup="showUploadPopup = false"/>
    </view>
  </view>
</template>

<style scoped lang="scss">
.print-id-and-registration-a4 {
  padding: 40rpx 40rpx;
  background: #fff;
  border-radius: 20rpx;
  height: 1210rpx;
  text-align: center;
}

.upload-box {
  margin-top: 30rpx;
  background: #fff;
  padding: 40rpx;
  border-radius: 20rpx
}

.upload-id-card-box {
  padding: 4rpx;
  width: 280rpx;
  height: 190rpx;
  position: relative;
  border-radius: 16rpx;
  border: 2rpx dashed #1073FF;
}

.upload-id-card-box .uploaded-image {
  width: 270rpx;
  height: 180rpx;
  border-radius: 16rpx;
}

.icon-card-box {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
}

.icon-card {
  background-color: #FFFFFF;
  border-radius: 100%;
  padding: 20rpx;
  box-shadow: 0 0 23px 0 rgba(1, 1, 1, 0.25);
}

.registration-card-box {
  width: 524rpx;
  height: 384rpx;
  position: relative;
  border-radius: 16rpx;
  padding: 4rpx;
  border: 2rpx dashed #1073FF;
}

.registration {
  width: 510rpx;
  height: 370rpx;
  border-radius: 16rpx;
}

.id-close-icon-box {
  position: absolute;
  top: 14rpx;
  right: 14rpx;
}
</style>